const { app, BrowserWindow, Menu, Tray } = require('electron')
const path = require('path')
const menuData = require('./menu')
const getSource = require('./menu/getSource')

const menu = Menu.buildFromTemplate(menuData)

const createWindow = async () => {

  const mainWindow = new BrowserWindow({
    width: 1000,
    height: 800,
    webPreferences: {
      preload: path.resolve(__dirname, './preload.js')
      // nodeIntegration: true,
      // contextIsolation: false
    }
  })
  
  mainWindow.loadFile('./index.html')
  
  mainWindow.webContents.openDevTools()
  
  Menu.setApplicationMenu(menu)
  
  mainWindow.webContents.on('context-menu', () => {
    menu.popup()
  })

  const tray = new Tray('trayTemplate@2x.png')
  
  tray.on('click', (e) => {
    if (e.shiftKey) {
      app.quit()
    } else {
      mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
    }
  })

  tray.setContextMenu(menu)

  getSource(mainWindow)
}

app.whenReady().then(() => {

  createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})